package com.reaml;

import com.entity.AdminUser;
import com.entity.VipUser;
import com.service.BaseService;
import com.service.admin.AdminUserService;
import com.service.imple.admin.AdminUserServiceImple;
import com.service.imple.home.VipUserServiceImple;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


//用户和权限验证的处理类
public class AuthReaml extends AuthorizingRealm {

	@Autowired
	protected VipUserServiceImple VaseService;

	//角色和权限验证的方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//添加角色信息
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		Set<String> roles=new HashSet<String>();
		roles.add("role1");
		roles.add("role2");
		simpleAuthorizationInfo.addRoles(roles); //将当期的用户添加角色
		
		//添加授权权限
		Set<String> pers=new HashSet<String>();
		pers.add("admin:index:index");
		pers.add("admin:index:roles");
//		pers.add("admin:index:add");
		
		simpleAuthorizationInfo.addStringPermissions(pers);
		
		return simpleAuthorizationInfo;
	}

	//用户验证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		String name = null;
		String pass = null;
		String userId = null;
		InetAddress ia=null;
		//用户名称
		String username= (String) token.getPrincipal();
		//获取密码
		String password=new String((char[])token.getCredentials());
			VipUser vipUser = new VipUser();
			vipUser.setUsername(username);
			List<VipUser> list = VaseService.selectAll(vipUser);
			name = list.get(0).getUsername();
			pass = list.get(0).getPassword();
			userId = String.valueOf(list.get(0).getId());
		try {
			ia=ia.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		String Ip=ia.getHostAddress();
		list.get(0).setLastLoginTime(new Date());
		list.get(0).setLastIp(Ip);
		VaseService.updateByPrimaryKeyWithBLOBs(list.get(0));


		if(!name.equals(username)) { //判断用户名
			throw new UnknownAccountException(); //如果用户名错误
		}

		if(!pass.equals(password)) { //判断密码
			throw new IncorrectCredentialsException();
		}

		SecurityUtils.getSubject().getSession().setAttribute("user",list.get(0));
		SecurityUtils.getSubject().getSession().setAttribute("userId",userId);
		//表示验证成功了
		return new SimpleAuthenticationInfo(username,password, userId);

	}

}
